<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>模板配置 - 代码生成器</title>
    <link rel="icon" type="image/svg+xml" href="/favicon.svg">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/codemirror@5.65.2/lib/codemirror.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/codemirror@5.65.2/theme/monokai.css">
    <style>
        .sidebar {
            min-height: 100vh;
            background-color: #343a40;
        }
        .sidebar .nav-link {
            color: #fff;
        }
        .sidebar .nav-link:hover {
            background-color: #495057;
            color: #fff;
        }
        .sidebar .nav-link.active {
            background-color: #007bff;
            color: #fff;
        }
        .main-content {
            padding: 20px;
        }
        .CodeMirror {
            height: 500px;
            border: 1px solid #ddd;
        }
        .template-item {
            cursor: pointer;
            transition: background-color 0.2s;
        }
        .template-item:hover {
            background-color: #f8f9fa;
        }
        .template-item.active {
            background-color: #007bff;
            color: white;
        }
        .group-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .group-actions {
            margin-top: 10px;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- 侧边栏 -->
            <nav class="col-md-2 d-md-block sidebar collapse">
                <div class="position-sticky pt-3">
                    <div class="text-center mb-4">
                        <h4 class="text-white">代码生成器</h4>
                    </div>
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link" href="/">
                                <i class="fa fa-home"></i> 首页
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="/database-config">
                                <i class="fa fa-database"></i> 数据库配置
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link active" href="/template-config">
                                <i class="fa fa-file-code-o"></i> 模板配置
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="/code-gen">
                                <i class="fa fa-cogs"></i> 代码生成
                            </a>
                        </li>
                    </ul>
                </div>
            </nav>

            <!-- 主内容区 -->
            <main class="col-md-10 ms-sm-auto main-content">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">模板配置</h1>
                </div>

                <!-- 模板组管理上栏 -->
                <div class="row mb-3">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-header group-header">
                                <h6 class="mb-0">模板组</h6>
                            </div>
                            <div class="card-body p-2">
                                <div class="d-flex align-items-center flex-wrap" id="templateGroupContainer">
                                    <div class="btn-group" role="group" id="templateGroupTabs">
                                        <!-- 模板组标签将通过JavaScript动态生成 -->
                                    </div>
                                    <button type="button" class="btn btn-info btn-sm ms-2" onclick="showAddGroupModal()" id="addGroupButton">
                                        <i class="fa fa-plus"></i>
                                    </button>
                                </div>
                                <!-- 模板组操作按钮 -->
                                <div class="group-actions">
                                    <button type="button" class="btn btn-primary btn-sm me-1" onclick="showAddTemplateModal()">
                                        <i class="fa fa-plus"></i> 添加模板
                                    </button>
                                    <button type="button" class="btn btn-success btn-sm me-1" onclick="saveTemplate()">
                                        <i class="fa fa-save"></i> 保存模板
                                    </button>
                                    <button type="button" class="btn btn-danger btn-sm me-1" onclick="deleteTemplate()">
                                        <i class="fa fa-trash"></i> 删除模板
                                    </button>
                                    <button type="button" class="btn btn-secondary btn-sm me-1" onclick="exportTemplates()">
                                        <i class="fa fa-download"></i> 导出模板
                                    </button>
                                    <button type="button" class="btn btn-secondary btn-sm" onclick="document.getElementById('importFile').click()">
                                        <i class="fa fa-upload"></i> 导入模板
                                    </button>
                                    <input type="file" id="importFile" style="display: none;" accept=".zip" onchange="importTemplates(event)">
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="row">
                    <!-- 模板列表 -->
                    <div class="col-md-3">
                        <div class="card">
                            <div class="card-header">
                                <h6 class="mb-0">模板列表</h6>
                            </div>
                            <div class="card-body p-0">
                                <div class="list-group list-group-flush" id="templateList">
                                    <!-- 模板列表将通过JavaScript动态生成 -->
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 模板编辑器 -->
                    <div class="col-md-9">
                        <div class="card">
                            <div class="card-header">
                                <h6 class="mb-0" id="currentTemplateName">选择模板进行编辑</h6>
                            </div>
                            <div class="card-body">
                                <div class="mb-3">
                                    <label for="fileNamePatternEditor" class="form-label">生成文件名模式</label>
                                    <input type="text" class="form-control" id="fileNamePatternEditor" placeholder="如: ${className}.java">
                                    <div class="form-text">使用FreeMarker模板语法定义生成的文件名模式</div>
                                </div>
                                <textarea id="templateEditor"></textarea>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 帮助信息 -->
                <div class="row mt-4">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-header">
                                <h6 class="mb-0">FreeMarker模板语法帮助</h6>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-6">
                                        <h6>常用变量：</h6>
                                        <ul class="list-unstyled">
                                            <li><code>${className}</code> - 类名（如：User）</li>
                                            <li><code>${classNameLowerFirst}</code> - 首字母小写类名（如：user）</li>
                                            <li><code>${tableName}</code> - 表名（如：t_user）</li>
                                            <li><code>${tableComment}</code> - 表注释</li>
                                            <li><code>${packageName}</code> - 包名</li>
                                            <li><code>${primaryKey}</code> - 主键信息</li>
                                        </ul>
                                    </div>
                                    <div class="col-md-6">
                                        <h6>字段列表循环：</h6>
                                        <pre><code>&lt;#list columns as column&gt;
    ${column.columnName} - 列名
    ${column.javaFieldName} - Java字段名
    ${column.javaType} - Java类型
    ${column.columnComment} - 列注释
    ${column.primaryKey?c} - 是否主键
&lt;/#list&gt;</code></pre>
                                    </div>
                                </div>
                                <div class="row mt-3">
                                    <div class="col-md-6">
                                        <h6>条件判断：</h6>
                                        <pre><code>&lt;#if column.primaryKey&gt;
    主键处理
&lt;#else&gt;
    普通字段处理
&lt;/#if&gt;</code></pre>
                                    </div>
                                    <div class="col-md-6">
                                        <h6>MyBatis参数：</h6>
                                        <pre><code>&lt;#noparse&gt;#{id}&lt;/#noparse&gt;
&lt;#noparse&gt;#{${column.javaFieldName}}&lt;/#noparse&gt;</code></pre>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <!-- 添加模板模态框 -->
    <div class="modal fade" id="addTemplateModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">添加新模板</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="addTemplateForm">
                        <div class="mb-3">
                            <label for="templateName" class="form-label">模板名称</label>
                            <input type="text" class="form-control" id="templateName" name="templateName" 
                                   placeholder="请输入模板名称（如：custom）" required>
                        </div>
                        
                        <div class="mb-3">
                            <label for="templateDescription" class="form-label">模板描述</label>
                            <textarea class="form-control" id="templateDescription" name="description" 
                                      rows="3" placeholder="请输入模板描述"></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="addTemplate()">添加</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加模板组模态框 -->
    <div class="modal fade" id="addGroupModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">添加新模板组</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="addGroupForm">
                        <div class="mb-3">
                            <label for="groupName" class="form-label">组名称</label>
                            <input type="text" class="form-control" id="groupName" name="groupName" 
                                   placeholder="请输入组名称" required>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="addTemplateGroup()">添加</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 修改模板组模态框 -->
    <div class="modal fade" id="editGroupModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">修改模板组</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="editGroupForm">
                        <input type="hidden" id="editGroupId" name="groupId">
                        <div class="mb-3">
                            <label for="editGroupName" class="form-label">组名称</label>
                            <input type="text" class="form-control" id="editGroupName" name="groupName" 
                                   placeholder="请输入组名称" required>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="updateTemplateGroup()">保存</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/codemirror@5.65.2/lib/codemirror.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/codemirror@5.65.2/mode/xml/xml.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/codemirror@5.65.2/mode/clike/clike.min.js"></script>
    <script>
        let editor;
        let currentTemplate = '';
        let currentGroup = 'default';
        let templateGroups = [];

        // 初始化编辑器
        document.addEventListener('DOMContentLoaded', function() {
            editor = CodeMirror.fromTextArea(document.getElementById('templateEditor'), {
                lineNumbers: true,
                mode: 'text/x-java',
                theme: 'monokai',
                indentUnit: 4,
                lineWrapping: true
            });

            // 加载模板组和模板数据
            loadTemplateGroups();
        });
        
        // 加载模板组数据
        function loadTemplateGroups() {
            return fetch('/template-config/groups')
                .then(response => response.json())
                .then(groups => {
                    templateGroups = groups;
                    renderTemplateGroups();
                    
                    // 默认选中第一个组
                    if (groups.length > 0) {
                        selectTemplateGroup(groups[0].id);
                    }
                })
                .catch(error => {
                    console.error('加载模板组失败:', error);
                    alert('加载模板组失败');
                    throw error; // 重新抛出错误，让调用者可以处理
                });
        }
        
        // 渲染模板组标签
        function renderTemplateGroups() {
            const container = document.getElementById('templateGroupTabs');
            container.innerHTML = '';
            
            templateGroups.forEach((group, index) => {
                // 只有在当前选中的模板组才显示小齿轮图标
                if (currentGroup === group.id) {
                    // 创建一个包含主按钮和下拉按钮的按钮组容器
                    const groupElement = document.createElement('div');
                    groupElement.className = 'btn-group';
                    groupElement.role = 'group';
                    
                    // 主按钮 - 模板组名称
                    const mainButton = document.createElement('button');
                    mainButton.type = 'button';
                    mainButton.className = `btn btn-outline-primary${currentGroup === group.id ? ' active' : ''}`;
                    mainButton.setAttribute('data-group-id', group.id);
                    mainButton.onclick = () => selectTemplateGroup(group.id);
                    mainButton.textContent = group.name;
                    
                    // 下拉按钮 - 小齿轮图标
                    const dropdownButton = document.createElement('button');
                    dropdownButton.type = 'button';
                    dropdownButton.className = `btn btn-outline-primary dropdown-toggle dropdown-toggle-split${currentGroup === group.id ? ' active' : ''}`;
                    dropdownButton.setAttribute('data-bs-toggle', 'dropdown');
                    dropdownButton.setAttribute('aria-expanded', 'false');
                    dropdownButton.innerHTML = '<i class="fa fa-cog"></i>';
                    
                    // 下拉菜单
                    const dropdownMenu = document.createElement('ul');
                    dropdownMenu.className = 'dropdown-menu';
                    
                    // 修改按钮
                    const editItem = document.createElement('li');
                    const editLink = document.createElement('a');
                    editLink.className = 'dropdown-item';
                    editLink.href = '#';
                    editLink.innerHTML = '<i class="fa fa-edit"></i> 修改';
                    editLink.onclick = (e) => {
                        e.preventDefault();
                        showEditGroupModal(group);
                    };
                    editItem.appendChild(editLink);
                    dropdownMenu.appendChild(editItem);
                    
                    // 删除按钮
                    const deleteItem = document.createElement('li');
                    const deleteLink = document.createElement('a');
                    deleteLink.className = 'dropdown-item';
                    deleteLink.href = '#';
                    deleteLink.innerHTML = '<i class="fa fa-trash"></i> 删除';
                    deleteLink.onclick = (e) => {
                        e.preventDefault();
                        deleteTemplateGroup(group.id);
                    };
                    deleteItem.appendChild(deleteLink);
                    dropdownMenu.appendChild(deleteItem);
                    
                    // 组装元素
                    groupElement.appendChild(mainButton);
                    groupElement.appendChild(dropdownButton);
                    groupElement.appendChild(dropdownMenu);
                    
                    container.appendChild(groupElement);
                } else {
                    // 未选中的模板组只显示名称
                    const mainButton = document.createElement('button');
                    mainButton.type = 'button';
                    mainButton.className = 'btn btn-outline-primary';
                    mainButton.setAttribute('data-group-id', group.id);
                    mainButton.onclick = () => selectTemplateGroup(group.id);
                    mainButton.textContent = group.name;
                    
                    container.appendChild(mainButton);
                }
            });
        }
        
        // 选择模板组
        function selectTemplateGroup(groupId) {
            currentGroup = groupId;
            
            // 更新标签按钮状态
            document.querySelectorAll('#templateGroupTabs button').forEach(btn => {
                btn.classList.remove('active');
                if (btn.getAttribute('data-group-id') === groupId) {
                    btn.classList.add('active');
                }
            });
            
            // 重新渲染模板组列表，确保只有当前选中的模板组显示齿轮图标
            renderTemplateGroups();
            
            // 重新加载数据后再渲染当前组的模板列表，确保显示最新数据
            loadTemplateGroupsForGroup(groupId);
        }
        
        // 为特定组加载数据并渲染模板列表
        function loadTemplateGroupsForGroup(groupId) {
            fetch('/template-config/groups')
                .then(response => response.json())
                .then(groups => {
                    templateGroups = groups;
                    renderTemplateList(groupId);
                })
                .catch(error => {
                    console.error('加载模板组失败:', error);
                    // 如果加载失败，仍然尝试渲染当前组
                    renderTemplateList(groupId);
                });
        }
        
        // 渲染模板列表
        function renderTemplateList(groupId) {
            const container = document.getElementById('templateList');
            container.innerHTML = '';
            
            const group = templateGroups.find(g => g.id === groupId);
            if (!group || !group.templates) {
                container.innerHTML = '<div class="p-3 text-center text-muted">暂无模板</div>';
                return;
            }
            
            group.templates.forEach((template, index) => {
                const item = document.createElement('div');
                item.className = `list-group-item template-item${index === 0 ? ' active' : ''}`;
                item.setAttribute('data-template', template.name);
                item.onclick = () => selectTemplate(item);
                
                // 使用模板名称而不是显示名称
                item.innerHTML = `
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h6 class="mb-1">${template.name}</h6>
                            <small>${template.description}</small>
                        </div>
                        ${template.enabled ? '<span class="badge bg-success">启用</span>' : '<span class="badge bg-secondary">禁用</span>'}
                    </div>
                `;
                
                container.appendChild(item);
            });
            
            // 默认选中第一个模板
            if (group.templates.length > 0) {
                const firstItem = container.querySelector('.template-item');
                if (firstItem) {
                    selectTemplate(firstItem);
                }
            }
        }

        // 选择模板
        function selectTemplate(element) {
            // 更新选中状态
            document.querySelectorAll('.template-item').forEach(item => {
                item.classList.remove('active');
            });
            element.classList.add('active');

            const templateName = element.getAttribute('data-template');
            currentTemplate = templateName;
            
            // 更新标题，使用模板名称而不是显示名称
            document.getElementById('currentTemplateName').textContent = templateName;

            // 加载模板内容
            fetch('/template-config/content/' + templateName)
                .then(response => response.text())
                .then(content => {
                    editor.setValue(content);
                    
                    // 根据文件类型设置语法高亮
                    if (templateName.endsWith('.ftl')) {
                        if (templateName.includes('xml')) {
                            editor.setOption('mode', 'xml');
                        } else {
                            editor.setOption('mode', 'text/x-java');
                        }
                    }
                })
                .catch(error => {
                    alert('加载模板失败：' + error);
                });
                
            // 加载模板信息（包括文件名模式）
            fetch('/template-config/groups')
                .then(response => response.json())
                .then(groups => {
                    let foundTemplate = null;
                    for (let group of groups) {
                        if (group.templates) {
                            foundTemplate = group.templates.find(t => t.name === templateName);
                            if (foundTemplate) break;
                        }
                    }
                    
                    if (foundTemplate) {
                        document.getElementById('fileNamePatternEditor').value = foundTemplate.fileNamePattern || '';
                    } else {
                        document.getElementById('fileNamePatternEditor').value = '';
                    }
                })
                .catch(error => {
                    console.error('加载模板信息失败：', error);
                    document.getElementById('fileNamePatternEditor').value = '';
                });
        }

        // 保存模板
        function saveTemplate() {
            if (!currentTemplate) {
                alert('请先选择一个模板');
                return;
            }

            const content = editor.getValue();
            const fileNamePattern = document.getElementById('fileNamePatternEditor').value;
            
            // 首先保存模板内容
            fetch('/template-config/save', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `templateName=${currentTemplate}&content=${encodeURIComponent(content)}`
            })
            .then(response => response.text())
            .then(data => {
                if (data === 'success') {
                    // 然后更新模板信息（包括文件名模式）
                    return fetch('/template-config/update-template-info', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({
                            name: currentTemplate,
                            fileNamePattern: fileNamePattern
                        })
                    });
                } else {
                    throw new Error('保存模板内容失败：' + data);
                }
            })
            .then(response => response.text())
            .then(data => {
                if (data === 'success') {
                    alert('保存成功！');
                } else {
                    alert('保存失败：' + data);
                }
            })
            .catch(error => {
                alert('保存失败：' + error);
            });
        }

        // 显示添加模板模态框
        function showAddTemplateModal() {
            // 清空表单
            document.getElementById('addTemplateForm').reset();
            // 显示模态框
            new bootstrap.Modal(document.getElementById('addTemplateModal')).show();
        }
        
        // 添加模板
        function addTemplate() {
            const form = document.getElementById('addTemplateForm');
            const formData = new FormData(form);
            
            // 获取模板名称并在后端自动添加.ftl后缀
            const templateName = formData.get('templateName');
            
            // 转换为 JSON，使用简化后的字段
            const templateData = {
                name: templateName,
                displayName: templateName, // 显示名称默认与模板名称相同
                description: formData.get('description'),
                templateType: 'java', // 默认模板类型
                groupId: currentGroup, // 使用当前选中的模板组
                enabled: true // 默认启用
            };
            
            fetch('/template-config/add', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(templateData)
            })
            .then(response => response.text())
            .then(data => {
                if (data === 'success') {
                    alert('模板添加成功！');
                    // 关闭模态框
                    bootstrap.Modal.getInstance(document.getElementById('addTemplateModal')).hide();
                    // 重新加载数据
                    loadTemplateGroups();
                } else {
                    alert('添加失败：' + data);
                }
            })
            .catch(error => {
                alert('添加失败：' + error);
            });
        }
        
        // 显示添加模板组模态框
        function showAddGroupModal() {
            const modal = new bootstrap.Modal(document.getElementById('addGroupModal'));
            // 清空表单
            document.getElementById('addGroupForm').reset();
            modal.show();
        }
        
        // 显示修改模板组模态框
        function showEditGroupModal(group) {
            const modal = new bootstrap.Modal(document.getElementById('editGroupModal'));
            // 填充表单数据
            document.getElementById('editGroupId').value = group.id;
            document.getElementById('editGroupName').value = group.name;
            modal.show();
        }
        
        // 添加模板组
        function addTemplateGroup() {
            const form = document.getElementById('addGroupForm');
            const formData = new FormData(form);
            
            const groupInfo = {
                name: formData.get('groupName'),
                description: '', // 默认空描述
                enabled: true // 默认启用
            };
            
            fetch('/template-config/groups/add', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(groupInfo)
            })
            .then(response => response.text())
            .then(result => {
                if (result === 'success') {
                    alert('模板组添加成功');
                    const modal = bootstrap.Modal.getInstance(document.getElementById('addGroupModal'));
                    modal.hide();
                    form.reset();
                    loadTemplateGroups(); // 重新加载数据
                } else {
                    alert(result);
                }
            })
            .catch(error => {
                alert('添加模板组失败: ' + error);
            });
        }
        
        // 更新模板组
        function updateTemplateGroup() {
            const form = document.getElementById('editGroupForm');
            const formData = new FormData(form);
            
            const groupInfo = {
                id: formData.get('groupId'),
                name: formData.get('groupName'),
                description: '', // 默认空描述
                enabled: true // 默认启用
            };
            
            // 这里需要实现更新模板组的接口
            // 暂时使用添加组的接口作为示例，实际需要后端支持更新接口
            fetch('/template-config/groups/update', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(groupInfo)
            })
            .then(response => response.text())
            .then(result => {
                if (result === 'success') {
                    alert('模板组更新成功');
                    const modal = bootstrap.Modal.getInstance(document.getElementById('editGroupModal'));
                    modal.hide();
                    loadTemplateGroups(); // 重新加载数据
                } else {
                    alert(result);
                }
            })
            .catch(error => {
                alert('更新模板组失败: ' + error);
            });
        }
        
        // 删除模板组
        function deleteTemplateGroup(groupId) {
            // 获取组名用于确认提示
            const group = templateGroups.find(g => g.id === groupId);
            const groupName = group ? group.name : '未知组';
            
            if (!confirm(`确定要删除模板组 "${groupName}" 吗？这将同时删除该组内的所有模板，删除后无法恢复！`)) {
                return;
            }
            
            fetch(`/template-config/groups/delete/${groupId}`, {
                method: 'DELETE'
            })
            .then(response => response.text())
            .then(result => {
                if (result === 'success') {
                    alert('模板组删除成功');
                    loadTemplateGroups(); // 重新加载数据
                } else {
                    alert(result);
                }
            })
            .catch(error => {
                alert('删除模板组失败: ' + error);
            });
        }
        
        // 删除模板
        function deleteTemplate() {
            if (!currentTemplate) {
                alert('请先选择一个模板');
                return;
            }
            
            // 检查是否为系统默认模板
<!--            const systemTemplates = ['entity.ftl', 'controller.ftl', 'service.ftl', 'mapper.ftl', 'mapperXml.ftl'];-->
<!--            if (systemTemplates.includes(currentTemplate)) {-->
<!--                alert('系统默认模板不可删除！');-->
<!--                return;-->
<!--            }-->

            if (!confirm('确定要删除模板 "' + currentTemplate + '"吗？此操作不可撤销！')) {
                return;
            }

            fetch('/template-config/delete/' + currentTemplate, {
                method: 'DELETE'
            })
            .then(response => response.text())
            .then(data => {
                if (data === 'success') {
                    alert('删除成功！');
                    // 重新加载数据
                    loadTemplateGroups();
                } else {
                    alert('删除失败：' + data);
                }
            })
            .catch(error => {
                alert('删除失败：' + error);
            });
        }
        
        // 导出模板
        function exportTemplates() {
            if (!currentGroup) {
                alert('请先选择一个模板组');
                return;
            }
            window.location.href = '/template-config/export/' + currentGroup;
        }
        
        // 导入模板
        function importTemplates(event) {
            if (!currentGroup) {
                alert('请先选择一个模板组');
                event.target.value = '';
                return;
            }
            
            const file = event.target.files[0];
            if (!file) {
                return;
            }
            
            console.log('开始导入模板到组:', currentGroup);
            
            const formData = new FormData();
            formData.append('file', file);
            
            // 显示导入中提示
            const originalBtnText = document.querySelector('[onclick="document.getElementById(\'importFile\').click()"]').innerHTML;
            document.querySelector('[onclick="document.getElementById(\'importFile\').click()"]').innerHTML = '<i class="fa fa-spinner fa-spin"></i> 导入中...';
            
            fetch('/template-config/import/' + currentGroup, {
                method: 'POST',
                body: formData
            })
            .then(response => {
                console.log('收到服务器响应:', response.status, response.statusText);
                return response.text();
            })
            .then(data => {
                console.log('导入结果:', data);
                if (data === 'success') {
                    alert('模板导入成功！');
                    // 重新加载数据并确保刷新当前组的模板列表
                    loadTemplateGroups()
                        .then(() => {
                            // 数据加载完成后，确保选择当前组并刷新模板列表
                            setTimeout(() => {
                                selectTemplateGroup(currentGroup);
                            }, 100);
                        })
                        .catch(error => {
                            console.error('重新加载数据失败:', error);
                            // 即使重新加载失败，也尝试选择当前组
                            selectTemplateGroup(currentGroup);
                        });
                } else {
                    console.error('导入失败:', data);
                    alert('导入失败：' + data);
                }
            })
            .catch(error => {
                console.error('导入请求失败:', error);
                alert('导入失败：' + error);
            })
            .finally(() => {
                // 清空文件输入框
                event.target.value = '';
                // 恢复按钮文本
                document.querySelector('[onclick="document.getElementById(\'importFile\').click()"]').innerHTML = originalBtnText;
            });
        }
    </script>
</body>
</html>